<template>
  <view class="container">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
         <uni-icons type="arrowleft" size="24" color="#000"></uni-icons>
        <text class="nav-title">返回</text>
      </view>

    </view>


    <!-- 聊天记录区域 -->
    <scroll-view class="chat-container" scroll-y :scroll-top="scrollTop" :scroll-with-animation="true"
      @scrolltoupper="loadMoreMessages" :scroll-into-view="lastMessageId" :scroll-anchoring="true" :enhanced="true"
      :bounces="true" :show-scrollbar="false" :scroll-animation-duration="300">
      <view class="message-list">
        <view v-for="(message, index) in messages" :key="index" :id="'msg-' + index"
          :class="['message-item', message.type === 'user' ? 'message-user' : 'message-ai']">
          <view class="message-content">
            <text v-if="message.type === 'user'">{{ message.content }}</text>
            <view v-else class="stream-content">
              <text>{{ message.content }}</text>
              <text v-if="message.isStreaming" class="streaming-indicator">▋</text>
              <text v-if="message.isStreaming && !message.content" class="waiting-hint">大概需要等待20s...</text>
            </view>
          </view>
          <text class="message-time">{{ message.time }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 输入框区域 -->
    <view class="input-container" :style="{ bottom: keyboardHeight + 'px' }">
      <view class="input-box">
        <input v-model="inputMessage" type="text" placeholder="请输入您的问题" confirm-type="send" @confirm="sendMessage"
          :adjust-position="false" :cursor-spacing="20" @focus="onFocus" @blur="onBlur" :disabled="isSending" />
        <button class="send-btn" @tap="sendMessage" :disabled="isSending">
          {{ isSending ? '发送中...' : '发送' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import UniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import { useProductStore } from '../../stores/product'
import { ChatService } from '../../utils/chatService'

const goBack = () => {
  uni.navigateBack()
}

interface Message {
    type: 'user' | 'ai'
    content: string
    time: string
    isStreaming?: boolean
  }

// 消息列表
const messages = ref<Message[]>([])
const inputMessage = ref('')
const keyboardHeight = ref(0)
const scrollTop = ref(0)
const isSending = ref(false)
const lastMessageId = ref('')

// 创建聊天服务实例，使用自定义API密钥和基础URL
const routeApiKey = ref('app-HHdHPdBaYcIVmu2OTWBuNJXm') // 默认值
const baseUrl = 'https://ai.yinlihupo.cc/v1'
const chatService = ref<ChatService>()

// 监听消息列表变化，自动滚动到最新消息
watch(messages, () => {
  nextTick(() => {
    if (messages.value.length > 0) {
      lastMessageId.value = 'msg-' + (messages.value.length - 1)
      scrollToBottom()
    }
  })
}, { deep: true })

// 在消息内容更新时也触发滚动
watch(() => messages.value.map(m => m.content).join(''), () => {
  nextTick(() => {
    if (messages.value.length > 0) {
      lastMessageId.value = 'msg-' + (messages.value.length - 1)
      scrollToBottom()
    }
  })
})

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isSending.value) return

  isSending.value = true
  const userMessage = inputMessage.value
  inputMessage.value = ''

  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: userMessage,
    time: new Date().toLocaleTimeString()
  })

  // 添加AI消息占位(清空内容以显示等待提示)
  const aiMessageIndex = messages.value.length
  messages.value.push({
    type: 'ai',
    content: '',
    time: new Date().toLocaleTimeString(),
    isStreaming: true
  })

  // 立即滚动到底部
  scrollToBottom()

  try {
    if (!chatService.value) {
      throw new Error('Chat service not initialized')
    }
    await chatService.value.sendMessage(
      userMessage,
      (message: Message) => {
        messages.value[aiMessageIndex] = message
        scrollToBottom()
      },
      () => {
        isSending.value = false
      }
    )
  } catch (error) {
    console.error('发送消息失败:', error)
    messages.value[aiMessageIndex].content = '抱歉，发送消息失败，请重试'
    messages.value[aiMessageIndex].isStreaming = false
    isSending.value = false
  }
}

// 修改滚动逻辑，使其在不同平台都能正常工作
const scrollToBottom = () => {
  // #ifdef H5
  const container = document.querySelector('.chat-container')
  if (container) {
    container.scrollTo({
      top: container.scrollHeight,
      behavior: 'smooth'
    })
  }
  // #endif

  // #ifdef MP-WEIXIN
  // 触发 scroll-view 的 scroll-into-view 到最新消息
  scrollTop.value = scrollTop.value + 1 // 触发更新
  // #endif
}

// 加载更多消息
const loadMoreMessages = () => {
  // 实现加载历史消息的逻辑
  console.log('加载更多消息')
}

// 键盘事件处理
const onFocus = (e: any) => {
  // #ifdef MP-WEIXIN
  keyboardHeight.value = e.detail.height || 0
  // #endif
  // #ifdef H5
  keyboardHeight.value = 0
  // #endif
  scrollToBottom()
}

const onBlur = () => {
  keyboardHeight.value = 0
}

// 页面加载时
onMounted(() => {
  scrollToBottom()
})

onLoad((options) => {
  if (options?.click_url) {
    routeApiKey.value = decodeURIComponent(options.click_url)
    console.log('55555', routeApiKey.value)
  }
  chatService.value = new ChatService(routeApiKey.value, baseUrl)

  // 获取产品列表并找到对应的opening消息
  const productStore = useProductStore()
  const product = productStore.agents.find(item => item.click_url === routeApiKey.value)

  // 如果找到产品且有opening消息，添加到消息列表
  if (product?.opening) {
    messages.value.push({
      type: 'ai',
      content: product.opening,
      time: new Date().toLocaleTimeString(),
      isStreaming: false
    })
  }
})
</script>

<style lang="scss">
/* 导航栏样式 */
.nav-bar {
  display: flex;
  align-items: center;
  padding: 30rpx;
  padding-top: calc(30rpx + var(--status-bar-height));
  background-color: #1f2128;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-back {
  padding-top: 35rpx;
  margin-right: 10rpx;
}

.nav-title {
  color: #fff;
  font-size: 30rpx;
  font-weight: bold;
}

/* 全局样式重置 */
.gradient-bar {
  justify-content: center;
  align-items: center;
  width: 820rpx;
  /* #ifdef H5 */
  position: sticky;
  top: 0;
  /* #endif */

  .gradient-bar {
    display: flex;
    align-items: center;
    border-radius: 40rpx;
    padding: 0 30rpx;
    height: 60rpx;
    background: linear-gradient(90deg, #7ed6df 0%, #70a1ff 50%, #e056fd 100%);
    color: #fff;
    font-size: 28rpx;
    font-weight: 400;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
    margin: 10rpx 20rpx;
    width: fit-content;
    min-width: 80%;
  }

  .gradient-bar .name {
    font-size: 32rpx;
    font-weight: bold;
    margin-right: 20rpx;
  }

  .gradient-bar .slogan {
    font-size: 24rpx;
    margin-right: 20rpx;
  }

  .gradient-bar .company {
    opacity: 0.9;
    font-size: 28rpx;
    margin-right: 20rpx;
  }
}

/* 聊天容器样式 */
.chat-container {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  padding: 20rpx;
  overflow-y: auto;
  overflow-x: hidden;
  margin-top: 0;
  transition: margin-top 0.3s ease;
  padding-bottom: 120rpx;
}

.compact-card+.chat-container {
  /* #ifdef H5 */
  margin-top: 40rpx;
  /* #endif */
  /* #ifdef MP-WEIXIN */
  margin-top: 120rpx;
  /* #endif */
}

.message-list {
  padding-bottom: 40rpx;
  width: 100%;
  box-sizing: border-box;
}

.message-item {
  margin-bottom: 30rpx;
  display: flex;
  flex-direction: column;
  max-width: 100%;
  box-sizing: border-box;
}

.message-user {
  align-items: flex-end;
}

.message-ai {
  align-items: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 20rpx;
  border-radius: 20rpx;
  font-size: 28rpx;
  word-break: break-all;
  box-sizing: border-box;
  white-space: pre-wrap;
}

.message-user .message-content {
  background-color: #646cff;
  color: #fff;
}

.message-ai .message-content {
  background-color: #3a3c4a;
  color: #fff;
}

.message-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.input-container {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #2c2e3a;
  padding: 20rpx;
  transition: all 0.3s;
  box-sizing: border-box;
  width: 100%;
  z-index: 99;
}

.input-box {
  display: flex;
  align-items: center;
  background-color: #3a3c4a;
  border-radius: 40rpx;
  padding: 10rpx 20rpx;
  box-sizing: border-box;
  width: 100%;

  input:disabled {
    opacity: 0.7;
  }
}

input {
  flex: 1;
  height: 80rpx;
  color: #fff;
  font-size: 28rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  width: 100%;
}

.send-btn {
  background-color: #646cff;
  color: #fff;
  font-size: 28rpx;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  margin: 0;
  line-height: 1.5;
  white-space: nowrap;

  &:disabled {
    background-color: #999;
    opacity: 0.7;
  }
}

.send-btn::after {
  border: none;
}

.stream-content {
  display: inline-block;
  position: relative;
}

.streaming-indicator {
  display: inline-block;
  margin-left: 2px;
  animation: blink 1s infinite;
  color: #646cff;
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0;
  }
}
</style>
